﻿using System;
using System.Data;
using System.Configuration;
using System.Collections;
using System.Web;
using System.Web.Security;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Web.UI.WebControls.WebParts;
using System.Web.UI.HtmlControls;
using Portal.BO.Editoral.Category;
using Portal.BO.Editoral.Vote;
using Portal.BO.Editoral.Newsedit;
using Portal.Core.DAL;
using Portal.BO.Editoral.LogNews;

namespace Portal.GUI.EditoralOffice.MainOffce.NewsAssign
{
    public partial class newsassign : System.Web.UI.UserControl
    {
        const string Thuc_Don_CatId = "77";
        protected void Page_Load(object sender, EventArgs e)
        {
            

            if (!IsPostBack)
            {
                CategoryHelper.Treebuild(cboCategory);
                objListNewsSource.SelectParameters[0].DefaultValue = "News_Status=3";
                if (Request.QueryString["thread"] == null)
                {
                    LinkSendAll.Visible = false;
                    ltrLinkSendAll.Visible = false;
                    lnkClear.Attributes.Add("onclick", "return ClearRelated('" + Request.QueryString["relat"] + "');");
                }
                else
                {
                    lnkAddRelatNews.Visible = false;
                }

            }


            // === Hidden Column
            string strType = Request.QueryString["type"] != null ? Request.QueryString["type"] : "";
            string cpmode = Request.QueryString["cpmode"] != null ? Request.QueryString["cpmode"] : "";

           
            if (strType.ToLower() == "news")
            {
                //grdListNews.Columns[0].Visible = true;
                //LinkSendAll.Visible = true;
                HideGridCol(4);

                lnkShowSelectedNews.Visible = false;
                ltrClear.Visible = false;
                ltrAddRelatNews.Visible = false;
            }
            else if (strType.ToLower() == "")
            {
                //string news_Id = Request.QueryString["news"] != null ? Request.QueryString["news"] : "";
                //if (news_Id == "")
                HideGridCol(4);

                lnkShowSelectedNews.Visible = false;
                ltrClear.Visible = false;
                ltrAddRelatNews.Visible = false;
                ltrLinkSendAll.Visible = false;
                lnkShowAllNews.Visible = false;
                ltrShowAllNews.Visible = false;
            }
            else if (strType.ToLower() == "vote")
            {
                //grdListNews.Columns[4].Visible = false;
            }
            else if (strType.ToLower() == "menu")
            {
                // Neu day la thuc don
                objListNewsSource.SelectParameters[0].DefaultValue = "News_Status=3 And Cat_ID = " + Thuc_Don_CatId;
                cboCategory.SelectedValue = Thuc_Don_CatId;
                cboCategory.Enabled = false;
                HideGridCol(0);
                spnSelectAll.Visible = false;
                spnUnselectAll.Visible = false;
                LinkSendAll.Visible = false;
                lnkAddRelatNews.Visible = false;
                lnkClear.Visible = false;
                ltrAddRelatNews.Visible = false;
                ltrLinkSendAll.Visible = false;
                ltrUnselectAll.Visible = false;
                ltrSelectAll.Visible = false;
            }
            else
            {
                // Nếu là chọn bài vào film hay chọn Bài vào sự kiện thì ẩn một số link
                HideGridCol(0);
                spnSelectAll.Visible = false;
                spnUnselectAll.Visible = false;
                LinkSendAll.Visible = false;
                lnkAddRelatNews.Visible = false;
                lnkClear.Visible = false;
                ltrAddRelatNews.Visible = false;
                ltrLinkSendAll.Visible = false;
                ltrUnselectAll.Visible = false;
                ltrSelectAll.Visible = false;

            }

            HideGridCol(6);
            HideGridCol(5);
            lnkClear.Visible = false;
            ltrClear.Visible = false;
            // ** ENd Hidden Column

            //txtKeyword.Attributes.Add("onkeypress", "return trapEnterKey(event, '" + btnSearch.ClientID + "')");
        }

        protected void LinkSendAll_Click(object sender, EventArgs e)
        {
            //String value = objThreaddetailSource.InsertParameters[0].DefaultValue = getCheckedRow();
            string strRelatedNews = txt_news_checked.Value.Trim();
            if (strRelatedNews.Length > 0)
                strRelatedNews = strRelatedNews.Substring(1);
            String value = objThreaddetailSource.InsertParameters[0].DefaultValue = strRelatedNews;

            objThreaddetailSource.Insert();

            //LogHelper logHelper = new LogHelper();
            //String Thread_Title = logHelper.GetTitleNewsThread(Convert.ToInt32(Request.QueryString["thread"]));
            
            //String[] News_ID = value.Split(',');
            //int TotalInsert = News_ID.Length;
            //LogRow logRow = new LogRow();
            //for (int i = 0; i < TotalInsert; i++)
            //{
            //    logRow.Object_ID = 0; logRow.News_ID = 0;
            //    logRow.Type = (int)LogType.FlowEvent;
            //    logRow.UserName = HttpContext.Current.User.Identity.Name;
            //    logRow.CreatedDate = DateTime.Now;
            //    String[] param = { logHelper.GetNewsTitle(Convert.ToInt64(News_ID[i])), Thread_Title};
            //    logRow.Action = LogListName.FLOW_EVENT + String.Format(Log.DUATIN_FLOWEVENT, param);
            //    logHelper.InsertFlowEvent(logRow);
            //}


            #region regist client script
                Page.RegisterClientScriptBlock("abc", "<script>this.opener.location.href='/office/threaddetails/" + Request.QueryString["thread"] + ".chn';this.close();</script>");
            #endregion
        }
        private string getCheckedRow()
        {
            string strDel = Request.Form["chkSelect"];
            /*foreach (GridViewRow grdRow in this.grdListNews.Rows)
            {
                if (grdRow.RowType == DataControlRowType.DataRow)
                {
                    CheckBox chkSel = (CheckBox)grdRow.Cells[0].FindControl("chkSelect");
                    if (chkSel.Checked)
                    {
                        HtmlInputHidden hdVal = (HtmlInputHidden)grdRow.Cells[4].FindControl("hdVal");
                        if (strDel != "")
                            strDel += ",";
                        strDel += hdVal.Value;
                    }
                }
            }*/
            if (strDel == null)
                return "";
            return strDel;
        }

        protected void cboPage_SelectedIndexChanged(object sender, EventArgs e)
        {
            grdListNews.PageIndex = Convert.ToInt32(cboPage.SelectedValue);
        }

        protected void btnSearch_Click(object sender, EventArgs e)
        {
            Portal.BO.SearchHelper objhelp = new Portal.BO.SearchHelper();
            string keyword = txtKeyword.Text.Trim().Replace("'", "");
            string[] strKeys = keyword.Split(" ".ToCharArray());
            string strKey = objhelp.getAndCond("News_Title", strKeys);
            string strCat = cboCategory.SelectedValue;
            string strAndCat = "";
            if (strCat != "0")
            {
                
                CategoryRow objCat = CategoryHelper.getCatInfoAsCategoryRow(Convert.ToInt32(strCat));
                if (objCat.Cat_ParentID == 0)
                {
                    strCat = CategoryHelper.GetChildCatIdByCatParentId(Convert.ToInt32(strCat));
                    if (strCat.Trim() != "")
                        strCat += "," + cboCategory.SelectedValue;
                    else
                        strCat = cboCategory.SelectedValue;
                }
                strAndCat = " AND Cat_ID IN (" + strCat + ")";
            }
            objListNewsSource.SelectParameters[0].DefaultValue = "News_Status=3 AND " + strKey + strAndCat;
        }

        protected void lnkShowAllNews_Click(object sender, EventArgs e)
        {
            Portal.BO.SearchHelper objhelp = new Portal.BO.SearchHelper();
            string[] strKeys = txtKeyword.Text.Split(" ".ToCharArray());
            string strKey = objhelp.getAndCond("News_Title", strKeys);
            string strCat = cboCategory.SelectedValue;
            string strAndCat = "";
            if (strCat != "0")
                strAndCat = " AND Cat_ID=" + strCat;
            objListNewsSource.SelectParameters[0].DefaultValue = "News_Status=3 AND " + strKey + strAndCat;

            grdListNews.DataBind();
            grdListNews.Columns[4].Visible = true;
        }

        protected void lnkAddRelatNews_Click(object sender, EventArgs e)
        {
            string strRelatID = "";
            if (Request.QueryString["relat"] != null)
            {
                strRelatID = Request.QueryString["relat"].ToString();
                //string strRelatedNews = getCheckedRow();
                string strRelatedNews = txt_news_checked.Value.Trim();
                if (strRelatedNews.Length > 0)
                    strRelatedNews = strRelatedNews.Substring(1);
                #region regist client script
                
                    Page.RegisterStartupScript("relatednews", "<script>AssignRelatedNews('" + strRelatID + "','" + strRelatedNews + "','" + txt_news_title_checked.ClientID + "',true);window.opener.BindDataForDropdown('hdRelatNews','hdRelatNewsTitle','cboNews','hdRelatNews');this.close();</script>");
                #endregion
            }
        }

        protected void lnkShowSelectedNews_Click(object sender, EventArgs e)
        {
            ShowSelectedNews();
            grdListNews.Columns[4].Visible = false;
        }

        private void ShowSelectedNews()
        {
            string strVoteId = Request.QueryString["voteid"] != null ? Request.QueryString["voteid"] : "";
            string strFilmId = Request.QueryString["filmid"] != null ? Request.QueryString["filmid"] : "";
            string newsid = Request.QueryString["news"] != null ? Request.QueryString["news"] : "";
            DataTable result = new DataTable();

            // lay nhung NewsID lien quan voi VoteId
            if (strVoteId.Trim() != "")
            {
                result = VoteHelper.GetVote_Assign__NewsId_ByVoteId(strVoteId);

            }

            
            if (result.Rows.Count > 0)
            {
                string strNews_id = result.Rows[0]["News_ID"].ToString();
                objListNewsSource.SelectParameters[0].DefaultValue = "News_Status=3 And News.News_Id = " + strNews_id;
                ShowGridCol(5);
            }
            else
            {
                // Neu khong co bai nao da chon thi hien thi trang
                objListNewsSource.SelectParameters[0].DefaultValue = "News_Status=3 And News.News_Id = -1";
            }

            // Lay nhung NewsID lien quan voi NewsId
            if (newsid.Trim() != "")
            {

                NewsRow objNewsRow = NewsEditHelper.GetNewsInfo(Convert.ToInt64(newsid.Trim()));
                if (objNewsRow.News_Relation != null && objNewsRow.News_Relation != "")
                {
                    objListNewsSource.SelectParameters[0].DefaultValue = "News_Status=3 And News.News_Id IN(" + objNewsRow.News_Relation + ")";
                    ShowGridCol(5);
                }
                else
                    objListNewsSource.SelectParameters[0].DefaultValue = "News_Status=3 And News.News_Id = -1";


            }
            grdListNews.DataBind();



        }

        private void HideGridCol(int _i)
        {
            grdListNews.Columns[_i].Visible = false;
        }

        private void ShowGridCol(int _i)
        {
            grdListNews.Columns[_i].Visible = true;
        }

        protected void grdListNews_RowCommand(object sender, GridViewCommandEventArgs e)
        {
            string strVoteId = Request.QueryString["voteid"] != null ? Request.QueryString["voteid"] : "";
            string strFilmId = Request.QueryString["filmid"] != null ? Request.QueryString["filmid"] : "";
            string newsid = Request.QueryString["news"] != null ? Request.QueryString["news"] : "";

            if (e.CommandName.ToLower() == "selectnews")
            {
                string strNewsId = e.CommandArgument.ToString();
                if (strVoteId.Trim() != "" && strNewsId.Trim() != "")
                {
                    VoteHelper.AssignNewsToVote(strNewsId, strVoteId);
                }


                if (Request.QueryString["type"] != null && Request.QueryString["type"].ToString() == "menu")
                {
                    // Thuc Don
                    string strHidID = Request.QueryString["relat"];
                    string strTitle = Request.QueryString["titleid"];
                    string news_title = Request.Form["hidNewsTitle" + strNewsId].ToString();
                    Page.RegisterStartupScript("AssignNewsToMenu", "<script>AssignNewsToMenu('" + strHidID + "','" + strTitle + "','" + strNewsId + "','" + news_title + "');this.close();</script>");
                }
                else
                    ShowSelectedNews();

            }

            if (e.CommandName == "DeleteSelectNews")
            {
                if (strVoteId.Trim() != "")
                {
                    VoteHelper.DeleteVote_Assigns_News_ByVote_ID(strVoteId);
                }

               

                if (newsid.Trim() != "")
                {
                    // Lay NewsId Relation ma se delete
                    string strNewsId_Relation = e.CommandArgument.ToString();
                    NewsEditHelper.DeleteNewsRelation(newsid, strNewsId_Relation);

                    #region Cap nhap NewsRelation vao Hidden Text o trang News Edit
                    // Bind lai NewsRelation vao hidden text o trang NewsEdit
                    strNewsId_Relation = NewsEditHelper.GetNewsByPrimaryKey(Convert.ToInt64(newsid)).News_Relation;
                    string strRelatID =  Request.QueryString["relat"];
                    if (strRelatID != null)
                        Page.RegisterStartupScript("relatednews", "<script>AssignRelatedNews('" + strRelatID + "','" + strNewsId_Relation + "');</script>");
                    #endregion
                }

                ShowSelectedNews();

            }
        }


        protected string IsCheck(string strNewsId)
        {
            //ViewState["media_id_checked" + cboPage.SelectedValue] = getCheckedRow();
            if (txt_news_checked.Value.Trim() != "")
            {
                string[] strArNewsId = txt_news_checked.Value.Trim().Split(',');
                foreach (string str in strArNewsId)
                {
                    if (str.Trim() == strNewsId)
                    {
                        return "checked";
                    }
                }
            }

            return "";


        }

        protected void grdListNews_RowDataBound(object sender, GridViewRowEventArgs e)
        {

        }

        protected void lnkClear_Click(object sender, EventArgs e)
        {

        }
    }
}